import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Button,
  Space,
  Typography,
  message,
  Breadcrumb,
  Form,
  Input,
  Divider,
  List,
  Avatar,
  Tag,
  Popconfirm,
} from 'antd';
import {
  MessageOutlined,
  SendOutlined,
  TeamOutlined,
  HomeOutlined,
  UserOutlined,
  LikeOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { getTopicDetail, getTopicReplies, replyTopic, getForumSections, increaseTopicViewCount, likeReply, likeTopic, deleteTopic, deleteReply } from '../../api/forum';
import { ForumTopic, ForumReply, ForumSection } from '../../types';
import { formatDateTime } from '../../utils/format';
import { useAuth } from '../../context/AuthContext';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const ForumTopicDetail: React.FC = () => {
  const { user } = useAuth();
  const { topicId } = useParams<{ topicId: string }>();
  const [topic, setTopic] = useState<ForumTopic | null>(null);
  const [section, setSection] = useState<ForumSection | null>(null);
  const [replies, setReplies] = useState<ForumReply[]>([]);
  const [loading, setLoading] = useState(true);
  const [replying, setReplying] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const hasViewedRef = useRef(false); // 防止重复增加查看次数

  useEffect(() => {
    if (topicId && !hasViewedRef.current) {
      hasViewedRef.current = true;
      fetchTopicDetail();
      fetchReplies();
      // 单独调用增加查看次数
      increaseViewCount();
    }
  }, [topicId]);

  const fetchTopicDetail = async () => {
    try {
      const response = await getTopicDetail(Number(topicId));
      if (response.code === 200) {
        setTopic(response.data);
        // 获取板块信息
        const sectionsResponse = await getForumSections();
        if (sectionsResponse.code === 200) {
          const currentSection = sectionsResponse.data.find(s => s.id === response.data.sectionId);
          setSection(currentSection || null);
        }
      } else {
        message.error('主题不存在');
        navigate('/forum');
      }
    } catch (error) {
      console.error('获取主题详情失败:', error);
      message.error('获取主题详情失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchReplies = async () => {
    try {
      const response = await getTopicReplies(Number(topicId), {
        page: 1,
        size: 100, // 简化实现，一次性加载所有回复
      });
      if (response.code === 200) {
        setReplies(response.data.records);
      }
    } catch (error) {
      console.error('获取回复失败:', error);
    }
  };

  const increaseViewCount = async () => {
    try {
      await increaseTopicViewCount(Number(topicId));
    } catch (error) {
      // 增加查看次数失败不影响用户体验，只在控制台记录
      console.log('增加查看次数失败:', error);
    }
  };

  const handleReply = async (values: any) => {
    try {
      setReplying(true);
      const response = await replyTopic(Number(topicId), {
        content: values.content,
      });
      if (response.code === 200) {
        message.success('回复成功');
        form.resetFields();
        fetchReplies(); // 重新加载回复列表
      } else {
        message.error(response.message || '回复失败');
      }
    } catch (error) {
      console.error('回复失败:', error);
      message.error('回复失败，请稍后重试');
    } finally {
      setReplying(false);
    }
  };

  const handleLikeReply = async (replyId: number) => {
    try {
      const reply = replies.find(r => r.id === replyId);
      const isLiked = reply?.isLiked;
      const response = await likeReply(replyId);
      if (response.code === 200) {
        const msg = isLiked ? '取消点赞成功' : '点赞成功';
        message.success(msg);
        fetchReplies(); // 重新加载回复列表
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败，请稍后重试');
    }
  };

  const handleLikeTopic = async () => {
    try {
      const isLiked = topic?.isLiked;
      const response = await likeTopic(Number(topicId));
      if (response.code === 200) {
        const msg = isLiked ? '取消点赞成功' : '点赞成功';
        message.success(msg);
        fetchTopicDetail(); // 重新加载主题详情
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败，请稍后重试');
    }
  };

  const handleDeleteTopic = async () => {
    try {
      const response = await deleteTopic(Number(topicId));
      if (response.code === 200) {
        message.success('主题删除成功');
        navigate(`/forum/sections/${topic?.sectionId}`);
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除主题失败:', error);
      message.error('删除失败，请稍后重试');
    }
  };

  const handleDeleteReply = async (replyId: number) => {
    try {
      const response = await deleteReply(replyId);
      if (response.code === 200) {
        message.success('回复删除成功');
        fetchReplies(); // 重新加载回复列表
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除回复失败:', error);
      message.error('删除失败，请稍后重试');
    }
  };

  // 检查是否可以删除主题
  const canDeleteTopic = () => {
    if (!user || !topic) return false;
    return user.userClass >= 4 || topic.authorId === user.id;
  };

  // 检查是否可以删除回复
  const canDeleteReply = (reply: ForumReply) => {
    if (!user) return false;
    return user.userClass >= 4 || reply.authorId === user.id;
  };

  if (loading) {
    return <Card loading />;
  }

  if (!topic) {
    return (
      <Card>
        <Text type="secondary">主题不存在</Text>
      </Card>
    );
  }

  return (
    <div>
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">
            <HomeOutlined />
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/forum">
            <TeamOutlined /> 论坛
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to={`/forum/sections/${topic.sectionId}`}>
            {section?.name}
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          {topic.title}
        </Breadcrumb.Item>
      </Breadcrumb>

      {/* 主题内容 */}
      <Card
        title={
          <Space>
            <MessageOutlined />
            <Title level={3} style={{ margin: 0 }}>
              {topic.title}
            </Title>
            <Space>
              {topic.isTop && <Tag color="red">置顶</Tag>}
              {topic.isEssence && <Tag color="gold">精华</Tag>}
              {topic.isLocked && <Tag color="default">锁定</Tag>}
            </Space>
          </Space>
        }
        extra={
          canDeleteTopic() && (
            <Popconfirm
              title="确定要删除这个主题吗？"
              onConfirm={handleDeleteTopic}
              okText="确定"
              cancelText="取消"
            >
              <Button type="text" danger icon={<DeleteOutlined />}>
                删除主题
              </Button>
            </Popconfirm>
          )
        }
        style={{ marginBottom: 16 }}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Space>
            <Avatar icon={<UserOutlined />} />
            <Space direction="vertical" size="small">
              <Link to={`/user/${topic.authorId}`}>
                <Text strong>{topic.username}</Text>
              </Link>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {formatDateTime(topic.createdAt)}
              </Text>
            </Space>
          </Space>
          <Divider />
          <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
            {topic.content}
          </Paragraph>
          <Divider />
          <Space>
            <Button
              type="text"
              icon={<LikeOutlined />}
              onClick={handleLikeTopic}
            >
              {topic?.isLiked ? '取消点赞' : '点赞'} ({topic?.likeCount || 0})
            </Button>
          </Space>
        </Space>
      </Card>

      {/* 回复列表 */}
      <Card title={`回复 (${replies.length})`} style={{ marginBottom: 16 }}>
        <List
          itemLayout="vertical"
          dataSource={replies}
          renderItem={(reply) => (
            <List.Item
              actions={[
                <Button
                  key="like"
                  type="text"
                  icon={<LikeOutlined />}
                  onClick={() => handleLikeReply(reply.id)}
                >
                  {reply.isLiked ? '取消点赞' : '点赞'} ({reply.likeCount || 0})
                </Button>,
                ...(canDeleteReply(reply) ? [
                  <Popconfirm
                    key="delete"
                    title="确定要删除这条回复吗？"
                    onConfirm={() => handleDeleteReply(reply.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="text" danger icon={<DeleteOutlined />}>
                      删除
                    </Button>
                  </Popconfirm>
                ] : [])
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Space>
                    <Link to={`/user/${reply.authorId}`}>
                      <Text strong>{reply.username}</Text>
                    </Link>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      #{reply.floor} • {formatDateTime(reply.createdAt)}
                    </Text>
                  </Space>
                }
                description={
                  <Paragraph style={{ whiteSpace: 'pre-wrap' }}>
                    {reply.content}
                  </Paragraph>
                }
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 回复表单 */}
      {!topic.isLocked && (
        <Card title="发表回复">
          <Form form={form} onFinish={handleReply}>
            <Form.Item
              name="content"
              rules={[
                { required: true, message: '请输入回复内容' },
                { min: 5, message: '回复内容至少5个字符' },
                { max: 2000, message: '回复内容不能超过2000个字符' },
              ]}
            >
              <TextArea
                rows={6}
                placeholder="请输入回复内容..."
                showCount
                maxLength={2000}
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={replying}
                  icon={<SendOutlined />}
                >
                  发表回复
                </Button>
                <Link to={`/forum/sections/${topic.sectionId}`}>
                  <Button>返回板块</Button>
                </Link>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      )}

      {topic.isLocked && (
        <Card>
          <Text type="secondary">此主题已被锁定，无法回复</Text>
        </Card>
      )}
    </div>
  );
};

export default ForumTopicDetail; 